<template>
  <div class="permission-list">
    <div class="page-header">
      <div class="header-content">
        <h1>权限管理</h1>
        <p class="subtitle">管理系统权限配置和层级结构</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd" class="action-btn">
          <el-icon><Plus /></el-icon>
          新增权限
        </el-button>
        <el-button @click="handleExpandAll" class="action-btn">
          <el-icon><Expand /></el-icon>
          展开全部
        </el-button>
        <el-button @click="handleCollapseAll" class="action-btn">
          <el-icon><Fold /></el-icon>
          折叠全部
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <div class="search-header">
        <el-icon><Search /></el-icon>
        <span>搜索筛选</span>
      </div>
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="权限名称" class="form-item">
          <el-input 
            v-model="searchForm.name" 
            placeholder="请输入权限名称"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="权限编码" class="form-item">
          <el-input 
            v-model="searchForm.code" 
            placeholder="请输入权限编码"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="权限类型" class="form-item">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable class="search-select">
            <el-option label="菜单" value="menu" />
            <el-option label="按钮" value="button" />
            <el-option label="接口" value="api" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" class="form-item">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable class="search-select">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item class="form-item">
          <el-button type="primary" @click="handleSearch" class="search-btn">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset" class="reset-btn">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 权限表格 -->
    <el-card class="table-card" shadow="never">
      <div class="table-header">
        <div class="table-info">
          <span class="info-text">共 {{ filteredPermissionList.length }} 条权限</span>
          <span v-if="selectedPermissions.length > 0" class="selected-info">
            已选择 {{ selectedPermissions.length }} 项
          </span>
        </div>
        <div class="table-actions">
          <el-button size="small" :disabled="selectedPermissions.length === 0" @click="handleBatchDelete">
            批量删除
          </el-button>
          <el-button size="small" :disabled="selectedPermissions.length === 0" @click="handleBatchStatus">
            批量状态
          </el-button>
        </div>
      </div>
      
      <div v-if="error" class="error-message">
        <el-icon><Warning /></el-icon>
        <span>{{ error }}</span>
      </div>
      
      <div v-if="loading" class="loading-container">
        <el-loading-spinner type="circle" size="large"></el-loading-spinner>
        <p>正在加载权限数据...</p>
      </div>
      
      <el-table 
        v-if="dataLoadSuccess" 
        :data="displayPermissionList" 
        class="permission-table"
        border
        stripe
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center">
          <template #default="scope">
            <span class="index-text">{{ (pagination.current - 1) * pagination.size + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="权限名称" min-width="150" />
        <el-table-column prop="code" label="权限编码" width="150" />
        <el-table-column label="权限类型" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.type)" size="small">
              {{ getTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路径" width="200" show-overflow-tooltip />
        <el-table-column prop="icon" label="图标" width="80" align="center">
          <template #default="scope">
            <el-icon v-if="scope.row.icon" class="permission-icon">
              <component :is="scope.row.icon" />
            </el-icon>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" align="center" />
        <el-table-column label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'" size="small">
              {{ scope.row.status === '1' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" align="center">
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="success" @click="handleAddChild(scope.row)">添加子级</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === '1' ? 'warning' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === '1' ? '禁用' : '启用' }}
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredPermissionList.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 权限表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="permissionFormRef"
        :model="permissionForm"
        :rules="permissionFormRules"
        label-width="100px"
        class="permission-form"
      >
        <el-form-item label="上级权限" prop="parentId">
          <el-tree-select
            v-model="permissionForm.parentId"
            :data="permissionTreeData"
            :props="treeSelectProps"
            placeholder="请选择上级权限"
            check-strictly
            :render-after-expand="false"
            class="tree-select"
          />
        </el-form-item>
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permissionForm.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="permissionForm.code" placeholder="请输入权限编码" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-radio-group v-model="permissionForm.type">
            <el-radio label="menu">菜单</el-radio>
            <el-radio label="button">按钮</el-radio>
            <el-radio label="api">接口</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="路径" prop="path" v-if="permissionForm.type === 'menu'">
          <el-input v-model="permissionForm.path" placeholder="请输入路径" />
        </el-form-item>
        <el-form-item label="图标" prop="icon" v-if="permissionForm.type === 'menu'">
          <el-input v-model="permissionForm.icon" placeholder="请输入图标名称" />
        </el-form-item>
        <el-form-item label="组件" prop="component" v-if="permissionForm.type === 'menu'">
          <el-input v-model="permissionForm.component" placeholder="请输入组件路径" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="permissionForm.sort" :min="0" :max="999" placeholder="请输入排序值" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="permissionForm.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="permissionForm.description" type="textarea" :rows="3" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { request } from '@/utils/request'
import { Plus, Search, Warning, Expand, Fold } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

export default defineComponent({
  name: 'PermissionList',
  components: {
    Plus,
    Search,
    Warning,
    Expand,
    Fold
  },
  setup() {
    // 响应式数据
    const loading = ref(false)
    const error = ref('')
    const dataLoadSuccess = ref(false)
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const submitLoading = ref(false)
    const selectedPermissions = ref([])
    const permissionFormRef = ref(null)

    // 权限列表数据
    const permissionList = ref([])
    const permissionTreeData = ref([])

    // 搜索表单
    const searchForm = reactive({
      name: '',
      code: '',
      type: '',
      status: ''
    })

    // 权限表单
    const permissionForm = reactive({
      id: '',
      parentId: null,
      name: '',
      code: '',
      type: 'menu',
      path: '',
      icon: '',
      component: '',
      sort: 0,
      status: '1',
      description: ''
    })

    // 分页配置
    const pagination = reactive({
      current: 1,
      size: 20
    })

    // 树选择配置
    const treeSelectProps = {
      children: 'children',
      label: 'name',
      value: 'id'
    }

    // 表单验证规则
    const permissionFormRules = {
      name: [
        { required: true, message: '请输入权限名称', trigger: 'blur' },
        { min: 2, max: 50, message: '权限名称长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      code: [
        { required: true, message: '请输入权限编码', trigger: 'blur' },
        { pattern: /^[A-Z_]+$/, message: '权限编码只能包含大写字母和下划线', trigger: 'blur' }
      ],
      type: [
        { required: true, message: '请选择权限类型', trigger: 'change' }
      ],
      path: [
        { required: true, message: '请输入路径', trigger: 'blur' }
      ],
      sort: [
        { required: true, message: '请输入排序值', trigger: 'blur' }
      ]
    }

    // 计算属性
    const filteredPermissionList = computed(() => {
      let filtered = permissionList.value

      if (searchForm.name) {
        filtered = filterTreeData(filtered, node => 
          node.name.toLowerCase().includes(searchForm.name.toLowerCase())
        )
      }

      if (searchForm.code) {
        filtered = filterTreeData(filtered, node => 
          node.code.toLowerCase().includes(searchForm.code.toLowerCase())
        )
      }

      if (searchForm.type) {
        filtered = filterTreeData(filtered, node => node.type === searchForm.type)
      }

      if (searchForm.status !== '') {
        filtered = filterTreeData(filtered, node => node.status === searchForm.status)
      }

      return filtered
    })

    const displayPermissionList = computed(() => {
      const start = (pagination.current - 1) * pagination.size
      const end = start + pagination.size
      return filteredPermissionList.value.slice(start, end)
    })

    const dialogTitle = computed(() => {
      return isEdit.value ? '编辑权限' : '新增权限'
    })

    // 方法
    const filterTreeData = (treeData, filterFn) => {
      const result = []
      
      const traverse = (nodes) => {
        nodes.forEach(node => {
          if (filterFn(node)) {
            const newNode = { ...node }
            if (node.children && node.children.length > 0) {
              newNode.children = traverse(node.children)
            }
            result.push(newNode)
          } else if (node.children && node.children.length > 0) {
            const filteredChildren = traverse(node.children)
            if (filteredChildren.length > 0) {
              const newNode = { ...node, children: filteredChildren }
              result.push(newNode)
            }
          }
        })
      }
      
      traverse(treeData)
      return result
    }

    const loadPermissionList = async () => {
      loading.value = true
      error.value = ''
      
      try {
        const response = await request.get('/permissions/tree')
        permissionList.value = response.data || []
        permissionTreeData.value = [{ id: 0, name: '顶级权限', children: response.data || [] }]
        dataLoadSuccess.value = true
      } catch (err) {
        error.value = '加载权限数据失败'
        console.error('Load permission list error:', err)
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      pagination.current = 1
    }

    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      pagination.current = 1
    }

    const handleAdd = () => {
      isEdit.value = false
      resetPermissionForm()
      dialogVisible.value = true
    }

    const handleAddChild = (row) => {
      isEdit.value = false
      resetPermissionForm()
      permissionForm.parentId = row.id
      dialogVisible.value = true
    }

    const handleEdit = (row) => {
      isEdit.value = true
      Object.assign(permissionForm, row)
      dialogVisible.value = true
    }

    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除权限 "${row.name}" 吗？删除后其子权限也将被删除！`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        await request.delete(`/permissions/${row.id}`)
        ElMessage.success('删除成功')
        loadPermissionList()
      } catch (err) {
        if (err !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    const handleToggleStatus = async (row) => {
      try {
        const newStatus = row.status === '1' ? '0' : '1'
        const statusText = newStatus === '1' ? '启用' : '禁用'
        
        await ElMessageBox.confirm(
          `确定要${statusText}权限 "${row.name}" 吗？`,
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        await request.put(`/permissions/${row.id}/status`, { status: newStatus })
        ElMessage.success(`${statusText}成功`)
        loadPermissionList()
      } catch (err) {
        if (err !== 'cancel') {
          ElMessage.error('操作失败')
        }
      }
    }

    const handleSubmit = async () => {
      if (!permissionFormRef.value) return
      
      try {
        await permissionFormRef.value.validate()
        submitLoading.value = true

        if (isEdit.value) {
          await request.put(`/permissions/${permissionForm.id}`, permissionForm)
          ElMessage.success('更新成功')
        } else {
          await request.post('/permissions', permissionForm)
          ElMessage.success('创建成功')
        }

        dialogVisible.value = false
        loadPermissionList()
      } catch (err) {
        if (err !== false) {
          ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
        }
      } finally {
        submitLoading.value = false
      }
    }

    const handleDialogClose = () => {
      resetPermissionForm()
      if (permissionFormRef.value) {
        permissionFormRef.value.resetFields()
      }
    }

    const resetPermissionForm = () => {
      Object.assign(permissionForm, {
        id: '',
        parentId: null,
        name: '',
        code: '',
        type: 'menu',
        path: '',
        icon: '',
        component: '',
        sort: 0,
        status: '1',
        description: ''
      })
    }

    const handleSelectionChange = (selection) => {
      selectedPermissions.value = selection
    }

    const handleBatchDelete = async () => {
      if (selectedPermissions.value.length === 0) return

      try {
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedPermissions.value.length} 个权限吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        const ids = selectedPermissions.value.map(permission => permission.id)
        await request.delete('/permissions/batch', { data: { ids } })
        ElMessage.success('批量删除成功')
        loadPermissionList()
      } catch (err) {
        if (err !== 'cancel') {
          ElMessage.error('批量删除失败')
        }
      }
    }

    const handleBatchStatus = async () => {
      if (selectedPermissions.value.length === 0) return

      try {
        const { value: status } = await ElMessageBox.prompt(
          '请输入状态值 (1: 启用, 0: 禁用)',
          '批量设置状态',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern: /^[01]$/,
            inputErrorMessage: '请输入 0 或 1'
          }
        )

        const ids = selectedPermissions.value.map(permission => permission.id)
        await request.put('/permissions/batch/status', { ids, status })
        ElMessage.success('批量设置成功')
        loadPermissionList()
      } catch (err) {
        if (err !== 'cancel') {
          ElMessage.error('批量设置失败')
        }
      }
    }

    const handleExpandAll = () => {
      // 这里可以通过表格的 ref 来展开所有行
      ElMessage.info('展开全部功能开发中...')
    }

    const handleCollapseAll = () => {
      // 这里可以通过表格的 ref 来折叠所有行
      ElMessage.info('折叠全部功能开发中...')
    }

    const handleSizeChange = (size) => {
      pagination.size = size
      pagination.current = 1
    }

    const handleCurrentChange = (current) => {
      pagination.current = current
    }

    const getTypeTagType = (type) => {
      const typeMap = {
        'menu': 'primary',
        'button': 'success',
        'api': 'warning'
      }
      return typeMap[type] || 'info'
    }

    const getTypeText = (type) => {
      const typeMap = {
        'menu': '菜单',
        'button': '按钮',
        'api': '接口'
      }
      return typeMap[type] || type
    }

    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      return dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss')
    }

    // 生命周期
    onMounted(() => {
      loadPermissionList()
    })

    return {
      loading,
      error,
      dataLoadSuccess,
      dialogVisible,
      isEdit,
      submitLoading,
      selectedPermissions,
      permissionFormRef,
      permissionList,
      permissionTreeData,
      treeSelectProps,
      searchForm,
      permissionForm,
      permissionFormRules,
      pagination,
      filteredPermissionList,
      displayPermissionList,
      dialogTitle,
      handleSearch,
      handleReset,
      handleAdd,
      handleAddChild,
      handleEdit,
      handleDelete,
      handleToggleStatus,
      handleSubmit,
      handleDialogClose,
      handleSelectionChange,
      handleBatchDelete,
      handleBatchStatus,
      handleExpandAll,
      handleCollapseAll,
      handleSizeChange,
      handleCurrentChange,
      getTypeTagType,
      getTypeText,
      formatDateTime
    }
  }
})
</script>

<style lang="scss" scoped>
@use '../../styles/variables.scss' as *;
@use '../../styles/responsive.scss' as *;
@use '../../styles/common.scss' as *;

.permission-list {
  padding: 20px;
  
  @include respond-to(xs) {
    padding: 12px;
  }
}

.page-header {
  @include flex-between;
  margin-bottom: 20px;
  
  @include respond-to(xs) {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .header-content {
    h1 {
      margin: 0 0 4px 0;
      font-size: 24px;
      font-weight: 600;
      color: var(--text-color-primary);
    }
    
    .subtitle {
      margin: 0;
      color: var(--text-color-secondary);
      font-size: 14px;
    }
  }
  
  .header-actions {
    @include flex-center;
    gap: 8px;
    
    .action-btn {
      @include flex-center;
      gap: 4px;
    }
  }
}

.search-card {
  margin-bottom: 20px;
  
  .search-header {
    @include flex-center;
    gap: 8px;
    margin-bottom: 16px;
    font-weight: 500;
    color: var(--text-color-primary);
  }
  
  .search-form {
    .form-item {
      margin-bottom: 12px;
      
      .search-input,
      .search-select {
        width: 200px;
        
        @include respond-to(xs) {
          width: 100%;
        }
      }
    }
    
    .search-btn,
    .reset-btn {
      @include flex-center;
      gap: 4px;
    }
  }
}

.table-card {
  .table-header {
    @include flex-between;
    margin-bottom: 16px;
    
    .table-info {
      @include flex-center;
      gap: 12px;
      
      .info-text {
        color: var(--text-color-secondary);
        font-size: 14px;
      }
      
      .selected-info {
        color: var(--primary-color);
        font-size: 14px;
        font-weight: 500;
      }
    }
  }
  
  .error-message {
    @include flex-center;
    gap: 8px;
    padding: 20px;
    color: var(--danger-color);
    background: var(--danger-bg);
    border-radius: 4px;
    margin-bottom: 16px;
  }
  
  .loading-container {
    @include flex-center;
    flex-direction: column;
    gap: 12px;
    padding: 40px;
    color: var(--text-color-secondary);
  }
}

.permission-table {
  .index-text {
    color: var(--text-color-secondary);
    font-size: 13px;
  }
  
  .permission-icon {
    font-size: 16px;
    color: var(--text-color-secondary);
  }
}

.pagination-container {
  @include flex-center;
  margin-top: 20px;
}

.permission-form {
  .el-form-item {
    margin-bottom: 20px;
  }
  
  .tree-select {
    width: 100%;
  }
}
</style> 